package com.bwie.bwedu.volley;

import android.content.Context;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bwie.bwedu.application.App;
import com.bwie.bwedu.bean.Student;
import com.bwie.bwedu.bean.response.BaseResponse;
import com.bwie.bwedu.bean.response.CommitResponse;
import com.bwie.bwedu.bean.response.EditStuResponse;
import com.bwie.bwedu.bean.response.InfoStudentResponse;
import com.bwie.bwedu.bean.response.MainInfoResponse;
import com.bwie.bwedu.bean.response.UserResponse;
import com.bwie.bwedu.model.AddStuListen;
import com.bwie.bwedu.net.Url;
import com.bwie.bwedu.utils.ASimpleCacheUtils;
import com.bwie.bwedu.utils.LogUtils;
import com.bwie.bwedu.utils.Md5Util;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.RequestBody;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by baofeng on 15/8/13.
 */
public class RequestAPI {

    /*
     * eg
     */
//    public static void selects(String result, Context context, Response.Listener<BaseResponse> listener, Response.ErrorListener errorListener){
//        Map<String,String> param = new HashMap<String, String>();
//        result="http://169.254.200.231:8080/ShopServer/myServlet?reqcode=202&type=2&keywords=";
//        //中文需转码
//        String s=    "三星";
//        //中文请求转码
////        MyRequest.doRequest(context, result,param, Request.Method.GET,BaseResponse.class,listener,errorListener);
//        MyRequest.doRequest(context, result+Uri.encode(s,"utf-8"),param, Request.Method.GET,BaseResponse.class,listener,errorListener);
//    }

    /*
    登陆
     */
    public static void login(String username, String pwd, Response.Listener<UserResponse> listener, Response.ErrorListener errorListener) {
        Map<String, String> param = new HashMap<String, String>();
        if (username.length() >= 8) {
            StringBuilder builder = new StringBuilder();
            builder.append(username.substring(username.length() - 8, username.length()));
            builder.reverse();
            username = new StringBuilder(username.substring(0, username.length() - 8)).append(builder).toString();
        }
        param.put("username", username);
        param.put("password", Md5Util.md5(pwd));
        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_LOGIN, param, Request.Method.POST, UserResponse.class, listener, errorListener);
    }

    /*
    获取主页信息（待确认、跟踪、本地、无效）
     */
    public static void getMainInfo(String flag, String pn, Response.Listener<MainInfoResponse> listener, Response.ErrorListener errorListener) {
        Map<String, String> param = new HashMap<String, String>();
        LogUtils.e("=========2333333333========="+flag);
        param.put("flag", flag);
        param.put("pn", pn);
        param.put("tk", ASimpleCacheUtils.read("tk"));
        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_MAIN, param, Request.Method.POST, MainInfoResponse.class, listener, errorListener);
    }

    public static void getHistory(String pn, String flag, String tk, Response.Listener<MainInfoResponse> listener, Response.ErrorListener errorListener) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("pn", pn);
        param.put("flag", flag);
        param.put("tk", tk);
        LogUtils.e("================" + tk);
        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_MAIN, param, Request.Method.POST, MainInfoResponse.class, listener, errorListener);
    }

    public static void pwdUpd(String newPwd, Response.Listener<BaseResponse> listener, Response.ErrorListener errorListener) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("npw", newPwd);
        param.put("tk", ASimpleCacheUtils.read("tk"));
        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_PWD_UPD, param, Request.Method.POST, BaseResponse.class, listener, errorListener);
    }

    /*
    提交无效学员信息
     */
    public static void invalid(String id, Response.Listener<MainInfoResponse> listener, Response.ErrorListener errorListener) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("id", id);
        param.put("tk", ASimpleCacheUtils.read("tk"));
        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_INVALID_SURE, param, Request.Method.POST, MainInfoResponse.class, listener, errorListener);
    }

    /*
    确认有效
     */
    public static void valid(String id, Response.Listener<BaseResponse> listener, Response.ErrorListener errorListener) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("id", id);
        param.put("tk", ASimpleCacheUtils.read("tk"));
        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_USERFUL_SURE, param, Request.Method.POST, BaseResponse.class, listener, errorListener);
    }

    /*
       获取代理人
        */
//    public static void getAgent(Response.Listener<BaseResponse> listener, Response.ErrorListener errorListener) {
//        Map<String, String> param = new HashMap<String, String>();
//        param.put("tk", ASimpleCacheUtils.read("tk"));
//        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_GET_AGENT, param, Request.Method.POST, BaseResponse.class, listener, errorListener);
//    }

    public static void getAgent(Context context, Response.Listener<String> listener, Response.ErrorListener errorListener) {

        RequestQueue mQueue = Volley.newRequestQueue(context);

        //        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST+Url.HTTP_REQUEST_GET_AGENT, param, Request.Method.POST, BaseResponse.class, listener, errorListener);

        StringRequest stringRequest = new StringRequest(Url.HTTP_HOST + Url.HTTP_REQUEST_GET_AGENT + "?tk=" + ASimpleCacheUtils.read("tk"), listener, errorListener);

        mQueue.add(stringRequest);

    }


    /*
    获取历史记录
     */
    public static void getHistort(String id, Response.Listener<InfoStudentResponse> listener, Response.ErrorListener errorListener) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("qdxxId", id);
        param.put("tk", ASimpleCacheUtils.read("tk"));
        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_HISTORY, param, Request.Method.POST, InfoStudentResponse.class, listener, errorListener);
    }

    /*
   删除本地保存
    */
    public static void localDel(String id, Response.Listener<BaseResponse> listener, Response.ErrorListener errorListener) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("qdxxId", id);
        param.put("tk", ASimpleCacheUtils.read("tk"));
        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_LOCAL_DEL, param, Request.Method.POST, BaseResponse.class, listener, errorListener);
    }

    /*
本地保存
 */
    public static void saveLocal(String per, String ptel, String stu, String stel, String adress, String IDcard, String id, String procurator, Response.Listener<BaseResponse> listener, Response.ErrorListener errorListener) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("id", "id");
        param.put("xm", stu);
        param.put("grsj", stel);
        param.put("xb", id);
        param.put("jg", adress);
        param.put("sfzh", IDcard);
        param.put("gxxm", per);
        param.put("gxdh", ptel);
        param.put("dlrid", procurator);
        param.put("tk", ASimpleCacheUtils.read("tk"));
        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_LOCAL_SAVE, param, Request.Method.POST, BaseResponse.class, listener, errorListener);
    }

//    /*
//   上传
//    */
//    public static void upLoading(String xm, String grsj, String xb, String jg, String sfzh, String gxxm, String gxdh, String dlrid, String zp) {
//        Map<String, String> param = new HashMap<String, String>();
//        param.put("xm", xm + "");
//        param.put("grsj", grsj + "");
//        param.put("xb", xb + "");
//        param.put("jg", jg + "");
//        param.put("sfzh", sfzh + "");
//        param.put("gxxm", gxxm + "");
//        param.put("gxdh", gxdh + "");
//        param.put("dlrid", dlrid + "");
//        param.put("tk", ASimpleCacheUtils.read("tk"));
//        OkHttpClient okHttpClient = new OkHttpClient();
//        MultipartBuilder fb = new MultipartBuilder()
//                .type(MultipartBuilder.FORM);
//        MediaType jpg = MediaType.parse("image/jpg");
//        for (Map.Entry<String, String> en : param.entrySet()) {
//            fb.addFormDataPart(en.getKey(), en.getValue());
//        }
//        Map<String, String> files = new HashMap<String, String>();
//        files.put("zp", zp + "");
//        for (Map.Entry<String, String> en : files.entrySet()) {
//            fb.addFormDataPart(en.getKey(), en.getKey(),
//                    RequestBody.create(jpg, new File(en.getValue())));
//        }
//        RequestBody formBody = fb.build();
//        com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(Url.HTTP_HOST + Url.HTTP_REQUEST_ADD).post(formBody).build();
//        try {
//            // 发送异步请求，同步会报错
//            okHttpClient.newCall(request).enqueue(new Callback() {
//
//                @Override
//                public void onFailure(com.squareup.okhttp.Request request, IOException e) {
//                    LogUtils.e("=====================" + "request = " + request.urlString() + "\ne.getLocalizedMessage() = "
//                            + e.getLocalizedMessage());
//                    System.out.println("request = " + request.urlString());
//                    System.out.println("e.getLocalizedMessage() = "
//                            + e.getLocalizedMessage());
//                }
//
//                @Override
//                public void onResponse(com.squareup.okhttp.Response response) throws IOException {
//                    // 看清楚是response.body().string()不是response.body().toString()
//                    if (response.isSuccessful()) {
//                        String s = response.body().string();
//                        LogUtils.e("=======================" + s);
//                    }
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
////        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST+Url.HTTP_REQUEST_ADD,param, Request.Method.POST,BaseResponse.class, listener,errorListener);
//    }

    /*
  上传
   */
    public static void upLoading(Student student, final AddStuListen listen) {
        LogUtils.e("===========requ1============");
        Map<String, String> param = new HashMap<String, String>();
        param.put("xm", student.xm + "");
        param.put("grsj", student.grsj + "");
        param.put("xb", student.xb + "");
        param.put("jg", student.jg + "");
        param.put("sfzh", student.sfzh + "");
        param.put("gxxm", student.gxxm + "");
        param.put("gxdh", student.gxdh + "");
        param.put("dlrid", student.dlrid + "");
        param.put("id", student.id + "");
        param.put("tk", ASimpleCacheUtils.read("tk"));
        LogUtils.e("======================="+student.id);
        OkHttpClient okHttpClient = new OkHttpClient();
        MultipartBuilder fb = new MultipartBuilder()
                .type(MultipartBuilder.FORM);
        MediaType jpg = MediaType.parse("image/jpg");
        for (Map.Entry<String, String> en : param.entrySet()) {
            fb.addFormDataPart(en.getKey(), en.getValue());
        }
        Map<String, String> files = new HashMap<String, String>();
        if (!TextUtils.isEmpty(student.zp)) {
            files.put("zp", student.zp + "");
        }
        for (Map.Entry<String, String> en : files.entrySet()) {
            fb.addFormDataPart(en.getKey(), en.getKey(),
                    RequestBody.create(jpg, new File(en.getValue())));
        }
        RequestBody formBody = fb.build();
        com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(Url.HTTP_HOST + Url.HTTP_REQUEST_ADD).post(formBody).build();
        try {
            // 发送异步请求，同步会报错
            okHttpClient.newCall(request).enqueue(new Callback() {

                @Override
                public void onFailure(com.squareup.okhttp.Request request, IOException e) {
                    LogUtils.e("=====================" + "request = " + request.urlString() + "\ne.getLocalizedMessage() = "
                            + e.getLocalizedMessage());
                    System.out.println("request = " + request.urlString());
                    System.out.println("e.getLocalizedMessage() = "
                            + e.getLocalizedMessage());
                    listen.onFail("上传失败！");
                }

                @Override
                public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                    // 看清楚是response.body().string()不是response.body().toString()
                    if (response.isSuccessful()) {
                        String s = response.body().string();
                        LogUtils.e("=======================" + s);
                        if (s != null && s.contains("操作成功")) {
                            CommitResponse com = new Gson().fromJson(s, CommitResponse.class);
                            listen.onSuccess(com.id);
                            return;
                        }
                    }
                    listen.onFail("上传失败！");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
 本地保存
  */
    public static void saveLocal(Student student, final AddStuListen listen) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("xm", student.xm + "");
        param.put("grsj", student.grsj + "");
        param.put("xb", student.xb + "");
        param.put("jg", student.jg + "");
        param.put("sfzh", student.sfzh + "");
        param.put("gxxm", student.gxxm + "");
        param.put("gxdh", student.gxdh + "");
        param.put("dlrid", student.dlrid + "");
        param.put("tk", ASimpleCacheUtils.read("tk"));
        OkHttpClient okHttpClient = new OkHttpClient();
        MultipartBuilder fb = new MultipartBuilder()
                .type(MultipartBuilder.FORM);
        MediaType jpg = MediaType.parse("image/jpg");
        for (Map.Entry<String, String> en : param.entrySet()) {
            fb.addFormDataPart(en.getKey(), en.getValue());
        }
        Map<String, String> files = new HashMap<String, String>();
        if (!TextUtils.isEmpty(student.zp)) {
            files.put("zp", student.zp + "");
        }
        for (Map.Entry<String, String> en : files.entrySet()) {
            fb.addFormDataPart(en.getKey(), en.getKey(),
                    RequestBody.create(jpg, new File(en.getValue())));
        }
        RequestBody formBody = fb.build();
        com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(Url.HTTP_HOST + Url.HTTP_REQUEST_LOCAL_SAVE).post(formBody).build();
        try {
            // 发送异步请求，同步会报错
            okHttpClient.newCall(request).enqueue(new Callback() {

                @Override
                public void onFailure(com.squareup.okhttp.Request request, IOException e) {
                    LogUtils.e("=====================" + "request = " + request.urlString() + "\ne.getLocalizedMessage() = "
                            + e.getLocalizedMessage());
                    System.out.println("request = " + request.urlString());
                    System.out.println("e.getLocalizedMessage() = "
                            + e.getLocalizedMessage());
                    listen.onFail("上传失败！");
                }

                @Override
                public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                    // 看清楚是response.body().string()不是response.body().toString()
                    if (response.isSuccessful()) {
                        String s = response.body().string();
                        LogUtils.e("=======================" + s);
                        if (s != null && s.contains("操作成功")) {
                            CommitResponse com = new Gson().fromJson(s, CommitResponse.class);
                            listen.onSuccess(com.id);
                            return;
                        }
                    }
                    listen.onFail("上传失败！");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void getVersion(String path,Response.Listener<String> listener, Response.ErrorListener errorListener) {

        RequestQueue mQueue = Volley.newRequestQueue(App.getContext());

        //        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST+Url.HTTP_REQUEST_GET_AGENT, param, Request.Method.POST, BaseResponse.class, listener, errorListener);

        StringRequest stringRequest = new StringRequest(path, listener, errorListener);

        mQueue.add(stringRequest);

    }


    /*
    编辑学员信息
     */
    public static void editStu(String id, Response.Listener<EditStuResponse> listener, Response.ErrorListener errorListener) {
        Map<String, String> param = new HashMap<String, String>();;
        param.put("id", id);
        param.put("tk", ASimpleCacheUtils.read("tk"));
        MyRequest.doRequest(App.getContext(), Url.HTTP_HOST + Url.HTTP_REQUEST_EDIT_STU, param, Request.Method.POST, EditStuResponse.class, listener, errorListener);
    }

}